﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAP.Connector;
using System.Configuration;
using CROSLAND.BL.BE;

namespace CROSLAND.DL.DALC.SAPC
{
    public class DALC
    {
        public static string Username = "";
        public static string Password = "";
        //public static UsuarioWebBE

        private static Connection createConnection()
        {
            string preFijo = ParametroDALC.getParamValueStatic("ConnType").ToLower();

            Destination dest = new Destination();
            dest.AppServerHost = ParametroDALC.getParamValueStatic(preFijo + "Ashost");
            dest.SystemNumber = Convert.ToInt16(ParametroDALC.getParamValueStatic(preFijo + "Sysnr"));
            dest.SAPRouterString = ParametroDALC.getParamValueStatic(preFijo + "Router");
            dest.Client = Convert.ToInt16(ParametroDALC.getParamValueStatic(preFijo + "Client"));

            if (CredencialesController.Usuario != null)
            {
                Username = CredencialesController.Usuario.UsuarioSap;
                Password = CredencialesController.Usuario.ClaveSap;
            }

            if (Username.Equals("") || Password.Equals(""))
            {
                dest.Password = ParametroDALC.getParamValueStatic(preFijo + "Passwd");
                dest.Username = ParametroDALC.getParamValueStatic(preFijo + "User");
            }
            else
            {
                dest.Password = Password;
                dest.Username = Username;
            }

            Connection conn = SAPConnectionPool.GetConnectionFromPool(dest.ConnectionString);

            try
            {
                if (!conn.IsOpen) { conn.Open(); }
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("timed out") >= 0 || ex.Message.IndexOf("timedout") >= 0 || ex.Message.IndexOf("timeout") >= 0)
                {
                    throw new Exception(ParametroDALC.getParamValueStatic("msgConnTimeOut"));
                }
                throw ex;
            }

            return conn;
        }
        
        public static Connection getConnection
        {
            get
            {
                return createConnection();
            }
        }
    }
}
